﻿using NLogManager;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace WJ.DataSender.Service.UdpAndTcp.Udp
{
    public class UdpReceiveService
    {
        /// <summary>
        /// 用于UDP发送的网络服务类
        /// </summary>
        static UdpClient udpcRecv = null;

        static IPEndPoint localIpep = null;

        /// <summary>
        /// 开关：在监听UDP报文阶段为true，否则为false
        /// </summary>
        static bool IsUdpcRecvStart = false;
        /// <summary>
        /// 线程：不断监听UDP报文
        /// </summary>
        static Thread thrRecv;

        public static void StartReceive(CancellationToken stoppingToken)
        {
            if (!IsUdpcRecvStart) // 未监听的情况，开始监听
            {
                localIpep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8899); // 本机IP和监听端口号
                udpcRecv = new UdpClient(localIpep);
                IsUdpcRecvStart = true;
                ReceiveMessage(stoppingToken);
                
            }
        }

        public static void StopReceive()
        {
            if (IsUdpcRecvStart)
            {
                udpcRecv.Close();
                IsUdpcRecvStart = false;
                LogHelper.Info("UDP监听器已成功关闭");
            }
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        private static void ReceiveMessage(CancellationToken stoppingToken)
        {
            while (IsUdpcRecvStart&& !stoppingToken.IsCancellationRequested)
            {
                LogHelper.Debug("UDP监听器正在监听端口：8899");
                try
                {
                    byte[] bytRecv = udpcRecv.Receive(ref localIpep);
                    string message = Encoding.UTF8.GetString(bytRecv, 0, bytRecv.Length);
                    LogHelper.Info($"{localIpep}{message}");
                    // To Do 接收到数据后调用TCP发送给第三方平台
                }
                catch (Exception ex)
                {
                    LogHelper.Fatal(ex.Message);
                    continue;
                }
            }
        }

    }
}
